import json
import os

def add_node_to_file(new_node,filename,wikipath):
    file_path = f"{wikipath}\\{filename}"

    if not os.path.exists(file_path):
        with open(file_path, 'w') as file:
            # 这里可以根据文件类型和需求写入相应的内容，对于新创建的文本文件，可以先写入空内容
            file.write("""
{
  "nodes": [],
  "edges": [],
  "metadata": {}
}
""")
        print(f"文件 {file_path} 已创建")
    else:
        print(f"文件 {file_path} 已存在")

    try:
        # 读取文件内容
        with open(file_path, 'r', encoding='utf-8') as file:
            canvasjson = json.load(file)
            try:
                 new_node['y'] = int(canvasjson["nodes"][len(canvasjson["nodes"]) - 1]['y']) + int(canvasjson["nodes"][len(canvasjson["nodes"]) - 1]['height']) + 20
            except Exception as e:
                new_node['y']=200
                print('没有获取到上一个节点',e)

        # 将新节点推入到canvasjson.nodes数组中
        if "nodes" in canvasjson:
            canvasjson["nodes"].append(new_node)
        else:
            canvasjson["nodes"] = [new_node]

        # 将更新后的内容写回文件
        with open(file_path, 'w', encoding='utf-8') as file:
            json.dump(canvasjson, file, indent=4)

    except FileNotFoundError:
        print(f"文件 {file_path} 不存在")
    except json.JSONDecodeError:
        print(f"文件 {file_path} 中的内容无法正确解析为JSON格式")


